<!-- 商品分类 -->
<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col ><el-button type="primary" @click="addCategoriesClick">添加用户</el-button></el-col>
      </el-row>
      <tree-table class="treeTable" :data='categoriesList' :columns='columns' :selection-type="false"
      :expand-type="false" show-index index-text="#" border :show-row-hover="false">
        <template slot='isOk' slot-scope="scope">
          <i class="el-icon-success" v-if="scope.row.cat_deleted ===false" style="color: lightgreen;"></i>
          <i class="el-icon-error" v-else style="color: lightgreen;"></i>
        </template>
        <template slot='order' slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag type="success" size="mini" v-else-if="scope.row.cat_level === 1">二级</el-tag>
          <el-tag type="danger" size="mini" v-else>三级</el-tag>
        </template>
        <template slot="opition" slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="btnEditClick(scope.row)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="btnDeleteClick(scope.row)">删除</el-button>
        </template>
      </tree-table>
      <!-- 底部分页 -->
      <el-pagination
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[1,2,5,10,50]"
        :current-page="queryInfo.pagenum"
        :page-size="queryInfo.pagesize"
        :total="total">
      </el-pagination>
    </el-card>
    <!-- 添加分类dialog -->
    <el-dialog title="添加分类"  :visible.sync="dialogAddVisible"
      width="50%"
      @close="addCategoriesDialogClosed">
      <!-- dialog主题区域 -->
      <el-form :model="addCatForm" :rules="addCatFormRules"
        ref="addFormRef" label-width="120px">
        <el-form-item label="* 分类名称" prop="roleName" >
          <el-input v-model="addCatForm.cat_name" autocomplete="off" ></el-input>
        </el-form-item>
        <el-form-item label="父级分类" prop="roleDes" >
          <el-cascader
          size="mini"
          clearable
          :options="parentCateList"
          v-model="catSelectCascaderKeysValue"
          :props="catCascaderProps"
          @change="catCascaderChange">
          </el-cascader>
        </el-form-item>
      </el-form>
        <!-- dialog底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogAddVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCategoriesDialogClick">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改 -->
    <el-dialog title="编辑分类"  :visible.sync="dialogEditVisible"
      width="50%"
      @close="editCatDialogClosed">
      <!-- dialog主题区域 -->
      <el-form :model="editCatForm" :rules="addCatFormRules"
        ref="editFormRef" label-width="120px">
        <el-form-item label="* 分类名称" prop="roleName" >
          <el-input v-model="editCatForm.cat_name" autocomplete="off" ></el-input>
        </el-form-item>
      </el-form>
        <!-- dialog底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogEditVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCatDialogClick">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created () {
    this.getCategoriesList()
  },
  data () {
    return {
      queryInfo: {
        type: '',
        pagenum: 1,
        pagesize: 10
      },
      categoriesList: [],
      total: 0,
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name'
        },
        {
          label: '是否有效',
          prop: '',
          type: 'template',
          template: 'isOk'
        },
        {
          label: '排序',
          type: 'template',
          template: 'order'
        },
        {
          label: '操作',
          type: 'template',
          template: 'opition'
        }
      ],
      dialogAddVisible: false,
      addCatForm: {
        cat_name: '',
        cat_pid: 0,
        cat_level: 0
      },
      addCatFormRules: {
        cat_name: [{
          required: true,
          message: '请输入分类名称',
          trigger: 'blur'
        }]
      },
      parentCateList: [],
      catCascaderProps: {
        checkStrictly: true,
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      catSelectCascaderKeysValue: [],
      editCatForm: {},
      dialogEditVisible: false
    }
  },
  methods: {
    // 获取分类list
    async getCategoriesList () {
      const { data: res } = await this.$http.get('categories', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类失败')
      }
      this.categoriesList = res.data.result
      this.total = res.data.total
    },
    handleSizeChange (val) {
      this.queryInfo.pagesize = val
      this.getCategoriesList()
    },
    handleCurrentChange (val) {
      this.queryInfo.pagenum = val
      this.getCategoriesList()
    },
    // 添加分类点击事件
    addCategoriesClick () {
      this.getParentCateList()
      this.dialogAddVisible = true
    },
    // 获取父级分类列表
    async getParentCateList () {
      const { data: res } = await this.$http.get('categories', {
        params: {
          type: 2
        }
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取父级分类失败')
      }
      this.parentCateList = res.data
    },
    // 添加分类dialog关闭事件
    addCategoriesDialogClosed () {
      this.catSelectCascaderKeysValue = []
      this.addCatForm.cat_pid = 0
      this.addCatForm.cat_level = 0
      this.$refs.addFormRef.resetFields()
    },
    // 添加分类dialog确定事件
    addCategoriesDialogClick () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('categories', this.addCatForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加商品分类失败')
        }
        this.$message.success('添加商品分类成功')
        this.dialogAddVisible = false
        this.getCategoriesList()
      })
    },
    // 父级级联选择改变事件
    catCascaderChange () {
      // 将最后一个赋值到pid
      if (this.catSelectCascaderKeysValue.length > 0) {
        this.addCatForm.cat_pid = this.catSelectCascaderKeysValue[this.catSelectCascaderKeysValue.length - 1]
        this.addCatForm.cat_level = this.catSelectCascaderKeysValue.length
      } else {
        this.addCatForm.cat_pid = 0
        this.addCatForm.cat_level = 0
      }
    },
    // 编辑点击事件
    async btnEditClick (cat) {
      const { data: res } = await this.$http.get(`categories/${cat.cat_id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('获取单个商品分类失败')
      }
      console.log(res.data)
      this.editCatForm = res.data
      this.dialogEditVisible = true
    },
    // 编辑dialog关闭事件
    editCatDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    // 编辑dialog确定事件
    editCatDialogClick () {
      this.$refs.editFormRef.validate(async (isTrue, obj) => {
        if (!isTrue) return
        let { data: res } = await this.$http.put(`categories/${this.editCatForm.cat_id}`, {
          cat_name: this.editCatForm.cat_name
        })
        // console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('更新商品分类失败')
        }
        this.$message.success('更新商品分类成功！')
        this.getCategoriesList()
        this.dialogEditVisible = false
      })
    },
    // 删除点击事件
    async btnDeleteClick (cat) {
      const confirmResult = await this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      let { data: res } = await this.$http.delete(`categories/${cat.cat_id}`)
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.$message.success('删除分类成功')
      this.getCategoriesList()
    }
  }
}

</script>
<style lang='less' scoped>
.treeTable{
  margin-top: 15px;
}
</style>
